//
//  WBHomeTableViewController.swift
//  Weibo
//
//  Created by xu on 2017/3/18.
//  Copyright © 2017年 xuantong. All rights reserved.
//

import UIKit

private let CELLID = "reuseIdentifier"

class WBHomeTableViewController: WBBaseTableViewController {
    
    //实例化home模型
    var homeViewModel:WBHomeViewModel = WBHomeViewModel()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //实例化按钮
        let btn = UIButton ()
        
        //自适应大小
        btn.sizeToFit()
        
        //添加图片
        btn.setImage(#imageLiteral(resourceName: "navigationbar_pop"), for:.normal)
        btn.setImage(#imageLiteral(resourceName: "navigationbar_pop_highlighted"), for: .highlighted)
        
        //按钮点击事件
        btn.addTarget(self, action: #selector(push), for: .touchUpInside)
        //设置右边导航栏的按钮
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView:btn)
     
        if !userLogin {
            //设置访客视图的信息 --> 获取访客视图
            visitorView.updateInfo(title: "关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon",isHome: true)
            
            return
     }
        
        setupUI()
        //加载数据
        setupTableViewInfo()
        loadData()
    }
    
    
    //MARK: 设置控件
    private func setupUI() {
        //添加控件
    navigationController?.view.insertSubview(pullDownTipLabel, belowSubview: navigationController!.navigationBar)
        
        
        
    }
    
  
    
    //MARK: 懒加载添加风火轮控件 加载更多
    fileprivate lazy var footerView :UIActivityIndicatorView = {
        
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        
        view.color = UIColor.orange
        
        return view
    }()
    
    
    
    
    
    //MARK: 系统下拉刷新控件
    fileprivate lazy var myRefreshControl: WBRefreshControl = {
        let view = WBRefreshControl()
        
        view.addTarget(self, action: #selector(refreshAction), for: UIControlEvents.valueChanged)
        
        return view
    }()
    
    
    // 下拉刷新提示控件
    
    fileprivate lazy var pullDownTipLabel:UILabel = {
        let lable = UILabel()
        lable.frame = CGRect(x: 0, y: 64-30, width:UIScreen.main.bounds.width, height: 30)
        lable.backgroundColor = UIColor.orange
        lable.textColor = UIColor.white
        lable.font = UIFont.systemFont(ofSize: FONTSIZEOFNORMAL)
        lable.textAlignment = .center
        // 一开始设置为隐藏状态
        lable.isHidden = true

        return lable
        
    }()
    
    
    
    // 设置下拉刷新提示控件动画 + 设置显示文字 -
     fileprivate func showpullDownTipLabel(count:Int) {
        
        // 防止用户快速刷新 导致pullDownTipLabel 重复下移的bug
       // 如果pullDownTipLabel.isHidde = false 就代表在执行动画 直接返回
        if self.pullDownTipLabel.isHidden == false {
            return
        }
        
        // 显示
        pullDownTipLabel.isHidden = false
        
        // 定义一个字符串
        var text = ""
        // 设置pullDownTipLabel显示的文字
        
        if count <= 0 {
            text = "您已经是最新的微博啦"
  
        }else{
            text = "您更新了\(count)条微博"
        }
        //赋值
        self.pullDownTipLabel.text = text
       
        // 设置动画叫下拉刷新提示控件 出来
        UIView.animate(withDuration:1, animations: {
            self.pullDownTipLabel.transform = CGAffineTransform(translationX: 0, y: 30)
            
        }) { (_) in
            
            // 在设置动画叫下拉刷新提示控件 回去
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
              
                self.pullDownTipLabel.transform = CGAffineTransform.identity
                
            }, completion: { (_) in
                //隐藏
                self.pullDownTipLabel.isHidden = true
            })
          
            
        }
    }
    
    @objc private func push() {
        //进入界面
        let demo = WBViewController()
        
        //设置底部栏的tabBar隐藏
        demo.hidesBottomBarWhenPushed = true
        
        //push界面
        self.navigationController?.pushViewController(demo, animated: true)
        
    }
    
}


//MARK:下拉刷新监听方法
extension WBHomeTableViewController{
    
    @objc fileprivate  func refreshAction()  {
        
        loadData()
    }
}


//MARK: 设置TableView相关信息
extension WBHomeTableViewController {
    
    fileprivate func setupTableViewInfo(){
       
        //注册
        tableView.register(WBHomeCell.self, forCellReuseIdentifier: CELLID)
        
        // 设置cell高度
        tableView.rowHeight = UITableViewAutomaticDimension
       
        //预估行高
        tableView.estimatedRowHeight = 200
        
        //隐藏分割线
        tableView.separatorStyle = .none
        
        //设置tableFooterView
        tableView.tableFooterView = footerView
        
        //添加下拉刷新(系统)
        tableView.addSubview(myRefreshControl)
        
              
    }
    
}


//MARK: 请求微博首页数据
extension WBHomeTableViewController{
    
    //MARK: 加载数据
    func loadData (){
        homeViewModel.getHomeData(isPullUp: footerView.isAnimating){ (isSuccess,count) in
            
            //停止风火轮
            self.endRefreshing()
           
            // 请求失败
            if !isSuccess {
                print("请求失败")
               // return
            }else{
           
            // 请求成功 ///刷新数据
              self.tableView.reloadData()
            // 如果是首次请求数据和下拉刷新再显示下拉刷新提示控件
              if !self.footerView.isAnimating {
                    self.showpullDownTipLabel(count: count)
                }
            }
        
          self.endRefreshing()
        }
    }
    
    
    fileprivate func endRefreshing(){
        // 停止风火轮的动画
        self.footerView.stopAnimating()
        self.myRefreshControl.endRefreshing()
    }
    
}




//MARK: tableView数据源方法

extension WBHomeTableViewController{
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.dataArray.count
        
    }
    
    
    override func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CELLID, for: indexPath)as! WBHomeCell
        cell.statusViewModel = homeViewModel.dataArray[indexPath.row]
        cell.selectionStyle = .none
        return cell
        
    }
    
    //cell将要显示的时候

    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == homeViewModel.dataArray.count - 1 && !footerView.isAnimating {
            
            // 开启动画
            footerView.startAnimating()
            //请求数据
            loadData()
        }
    }
    
    
}
